#include <map>
#include <vector>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include <string.h>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include "log.hpp"
#include "ThreadPool.hpp"
#include "Task.hpp"

#define portdefault 8088
#define ipdefault "0.0.0.0"

extern Log lg;
enum
{
    SOCKET = 1,
    LISTEN,
    BIND,
    ACCEPT
}; 
class Server
{
public:
    Server()
    {
    }
    Server(uint16_t port = portdefault, std::string ip = ipdefault)
        : port_(port), ip_(ip)
    {
    }
    void Init()
    {
        listensockfp_ = socket(AF_INET, SOCK_STREAM, 0);
        if (listensockfp_ < 0)
        {
            lg(Fatal, "socket create fail: %s, errno: %d", strerror(errno), errno);
            exit(SOCKET);
        }
        struct sockaddr_in Server;
        bzero(&Server, sizeof(Server));
        Server.sin_port = htons(port_);
        Server.sin_addr.s_addr = inet_addr(ip_.c_str());
        Server.sin_family = AF_INET;
        if (bind(listensockfp_, (const sockaddr *)&Server, sizeof(Server)) < 0)
        {
            lg(Fatal, "bind Error: %s,errno: %d", strerror(errno), errno);
            exit(BIND);
        }
        if (listen(listensockfp_, 10) < 0)
        {
            lg(Fatal, "listen Error: %s, errno: %d", strerror(errno), errno);
            exit(LISTEN);
        }
        lg(Info, "TCPServer Init");
    }
    void Run()
    {
        ThreadPool<Task>::GetInstance()->Start();
        lg(Info, "TcpSever is running....");
        while (true)
        {
            sockaddr_in Cilent;
            memset(&Cilent, 0, sizeof(Cilent));
            socklen_t len = sizeof(Cilent);
            //接收accept
            int sockfp = accept(listensockfp_, (struct sockaddr *)&Cilent, &len);
            if(sockfp < 0)
            {
                lg(Warning, "accept Error: %s, errno: %d", strerror(errno), errno);
                exit(ACCEPT);
            }
            // char cilentip[32];
            std::string cilentip;
            uint16_t port = ntohs(Cilent.sin_port);
            cilentip = inet_ntoa(Cilent.sin_addr);
            Task t(listensockfp_, cilentip.c_str(), port);
            ThreadPool<Task>::GetInstance()->Push(t);
        }
    }
    ~Server()
    {}

private:
    uint16_t port_;
    std::string ip_;
    int listensockfp_ = -1;
    int tcpsocketfp_ = -1;
};